<template>
  <router-view v-if="route.matched.length === 3" @updated="loadData" />
  <div v-else>
    <a-spin :spinning="loading">
      <search-box :show-search="false" :show-reset="false" @search="handleSearch" @reset="handleReset">
        <div style="position: relative">
          <div style="display: flex; flex-wrap: wrap; align-content: space-around">
            <div class="search-item">
              <div class="search-text">Client Name</div>
              <a-input v-model:value="searchStruct.clientName" />
            </div>
            <div class="search-item">
              <div class="search-text">Country/Region</div>
              <e-country-region-select v-model="countryIDWrapped" :allow-clear="true" />
            </div>
            <div class="search-item">
              <div class="search-text">URL</div>
              <a-input v-model:value="searchStruct.url" />
            </div>
            <div class="search-item">
              <div class="search-text">From</div>
              <a-date-picker
                v-model:value="searchStruct.beginTime"
                :disabled-date="disabledDateStart"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
            <div class="search-item">
              <div class="search-text">To</div>
              <a-date-picker
                v-model:value="searchStruct.endTime"
                :disabled-date="disabledDateEnd"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
            <div style="height: 60px; width: 150px"></div>
          </div>
          <a-space class="buttons" style="position: absolute; right: 0; bottom: 0">
            <a-button @click="handleReset">Reset</a-button>
            <a-button class="secondary" @click="handleSearch">Search</a-button>
          </a-space>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Phase Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="phase in filter.clientPhaseLists"
              :key="phase.id"
              v-model="phase.checked"
              @change="handleFilterChange.phase[phase.phaseName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ phase.count }}</span> {{ phase.phaseName }}
            </e-checkbox>
          </div>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Status Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="status in filter.clientStatusLists"
              :key="status.id"
              v-model="status.checked"
              @change="handleFilterChange.status[status.statusName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ status.count }}</span> {{ status.statusName }}
            </e-checkbox>
          </div>
        </div>
        <a-divider dashed />
        <div class="filter">
          <span class="title">Client Tier Select (MultiSelect)</span>
          <div class="options">
            <e-checkbox
              v-for="tier in filter.clientTierLists"
              :key="tier.id"
              v-model="tier.checked"
              @change="handleFilterChange.tier[tier.tierName === 'All' ? 'All' : 'Other']"
            >
              <span class="count">{{ tier.count }}</span> {{ tier.tierName }}
            </e-checkbox>
          </div>
        </div>
      </search-box>
      <e-container class="table">
        <a-table
          class="ant-table-striped"
          :columns="Columns"
          :data-source="listData"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
          row-key="id"
          table-layout="fixed"
          :pagination="pageOption"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'tags'">
              <e-tags-field :client="record" />
            </template>
            <template v-if="column.key === 'countryID'">
              <e-country-or-region :code="record.countryID" />
            </template>
            <template v-if="column.key === 'status'">
              <e-client-status :status="record.status"></e-client-status>
            </template>
            <template v-if="column.key === 'fullName'">
              <a-space>
                <a-tooltip>
                  <template #title> Do not contact this client </template>
                  <e-icon v-if="record.fromMLV" type="tips1" fontSize="14px" style="color: #ffaf17; cursor: help" />
                </a-tooltip>
                <a
                  :href="router.resolve({ name: 'Client Detail', params: { id: record.id } }).href"
                  :target="record.id"
                >
                  {{ record.fullName }}
                </a>
              </a-space>
            </template>
          </template>
          <template #emptyText><e-empty /></template>
        </a-table>
      </e-container>
    </a-spin>
    <!-- 待审核列表 -->
    <pending-clients v-model:display="displayPendingClients" :get-pending-clients="TargetClient.getPendingClients" />
    <!-- 传送到父组件的Title Bar上 -->
    <Teleport v-if="isMounted" to="#title-right-teleport-from-child">
      <a-space>
        <a-button type="link" @click="displayPendingClients = true"> List Of Pending Clients </a-button>
        <a-button type="primary" @click="handleClickCreate">
          <template #icon> <e-icon type="add" color="white" font-size="18px" style="margin-right: 12px" /> </template>
          Create New Client
        </a-button>
      </a-space>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import EContainer from '@/components/EContainer.vue'
import EEmpty from '@/components/EEmpty.vue'
import EIcon from '@/components/EIcon.vue'
import SearchBox from '@/pages/components/Search.vue'
import ECheckbox from '@/components/ECheckbox.vue'
import TargetClient from '@/api/targetClient.js'
import ECountryRegionSelect from '@/components/ECountryRegionSelect.vue'
import ECountryOrRegion from '@/components/ECountryOrRegion.vue'
import EClientStatus from '@/components/EClientStatus.vue'
import ETagsField from '@/components/ETagsField.vue'
import PendingClients from './index/components/PendingClients.vue'
import { useStore } from 'vuex'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import Columns from './columns.js'
import dayjs from 'dayjs'
import { CLIENT_IS_REACHED_LIMIT } from '@/constants/message.js'
const { message } = inject('Feedback')
const loading = ref(true)
const displayPendingClients = ref(false)
const listData = ref([])
const filter = ref({})
const pageOption = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: false,
  onChange(value) {
    this.current = value
    searchStruct.page.pageIndex = value
    loadData()
  }
})
const searchStruct = reactive({
  phaseID: [],
  tier: [],
  status: [],
  clientName: '',
  countryID: 0,
  url: '',
  page: { pageRows: 10, pageIndex: 1, total: 0, sort: undefined, order: undefined },
  beginTime: undefined,
  endTime: undefined
})
const disabledDateStart = current => {
  return (searchStruct.endTime ? current > dayjs(searchStruct.endTime) : false) || current > dayjs()
}
const disabledDateEnd = current => {
  return (searchStruct.beginTime ? current < dayjs(searchStruct.beginTime) : false) || current > dayjs()
}
const countryIDWrapped = useDictNullValue(searchStruct, 'countryID')
const isMounted = ref(false)
const route = useRoute()
const router = useRouter()
onMounted(() => {
  isMounted.value = true
})
const store = useStore()
store.dispatch('dict/getCountriesOrRegions')
store.dispatch('dict/getClientStatusTypes')
const loadConditions = () => {
  return new Promise(resolve => {
    TargetClient.getFilterConditions(
      searchStruct.clientName,
      searchStruct.countryID,
      searchStruct.url,
      searchStruct.beginTime,
      searchStruct.endTime
    ).then(res => {
      filter.value = reactive(res.data)
      filter.value.clientPhaseLists[0].checked = true
      filter.value.clientStatusLists[0].checked = true
      filter.value.clientTierLists[0].checked = true
      updateSearchStruct()
    })
    resolve()
  })
}
const loadData = () => {
  loading.value = true
  TargetClient.list(searchStruct)
    .then(res => {
      listData.value = res.data
      pageOption.total = res.total
    })
    .finally(() => {
      loading.value = false
    })
}
loadConditions().then(() => {
  loadData()
})
const updateSearchStruct = () => {
  pageOption.current = 1
  searchStruct.page.pageIndex = 1
  searchStruct.phaseID = filter.value.clientPhaseLists.filter(phase => phase.checked).map(phase => phase.id)
  searchStruct.status = filter.value.clientStatusLists.filter(status => status.checked).map(status => status.id)
  searchStruct.tier = filter.value.clientTierLists.filter(tier => tier.checked).map(tier => tier.id)
}

const handleFilterChange = {
  phase: {
    All: () => {
      const otherOptions = filter.value.clientPhaseLists.filter(phase => phase.id !== -2)
      const allOption = filter.value.clientPhaseLists[0]
      if (allOption.checked) {
        otherOptions.filter(phase => phase.checked !== -2).forEach(phase => (phase.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientPhaseLists.filter(phase => phase.id !== -2)
      const allOption = filter.value.clientPhaseLists[0]
      if (otherOptions.some(phase => phase.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(phase => !phase.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  },
  status: {
    All: () => {
      const otherOptions = filter.value.clientStatusLists.filter(status => status.id !== -2)
      const allOption = filter.value.clientStatusLists[0]
      if (allOption.checked) {
        otherOptions.filter(status => status.checked !== -2).forEach(status => (status.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientStatusLists.filter(status => status.id !== -2)
      const allOption = filter.value.clientStatusLists[0]
      if (otherOptions.some(status => status.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(status => !status.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  },
  tier: {
    All: () => {
      const otherOptions = filter.value.clientTierLists.filter(tier => tier.id !== -2)
      const allOption = filter.value.clientTierLists[0]
      if (allOption.checked) {
        otherOptions.filter(tier => tier.checked !== -2).forEach(tier => (tier.checked = false))
      }
      updateSearchStruct()
      loadData()
    },
    Other: () => {
      const otherOptions = filter.value.clientTierLists.filter(tier => tier.id !== -2)
      const allOption = filter.value.clientTierLists[0]
      if (otherOptions.some(tier => tier.checked)) {
        allOption.checked = false
      }
      if (otherOptions.every(tier => !tier.checked)) {
        allOption.checked = true
      }
      updateSearchStruct()
      loadData()
    }
  }
}
const handleTableChange = (page, filters, sorter) => {
  searchStruct.page.sort = sorter.order === undefined ? undefined : sorter.columnKey
  searchStruct.page.order = sorter.order === undefined ? undefined : sorter.order.substr(0, sorter.order.length - 3)
  loadData()
}
const handleSearch = () => {
  pageOption.current = 1
  searchStruct.page.pageIndex = 1
  loadConditions().then(() => {
    loadData()
  })
}
const handleReset = () => {
  searchStruct.phaseID = [-2]
  searchStruct.tier = [-2]
  searchStruct.status = [-2]
  searchStruct.clientName = ''
  searchStruct.countryID = 0
  searchStruct.beginTime = undefined
  searchStruct.endTime = undefined
  pageOption.current = 1
  searchStruct.page.pageIndex = 1
  loadConditions().then(() => {
    loadData()
  })
}
const handleClickCreate = () => {
  TargetClient.isAllowCreate().then(({ data }) => {
    if (data) {
      router.push(route.path + '/create')
    } else {
      message.warning(CLIENT_IS_REACHED_LIMIT)
    }
  })
}
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_table';
.page-search-components {
  .filter {
    color: @text-gray;
    .title {
      display: inline-block;
      width: 190px;
    }
    .options {
      display: inline-block;
      margin-left: 16px;
      .e-checkbox {
        &:not(:first-child) {
          margin-left: 32px;
        }
        .count {
          display: inline-block;
          height: 16px;
          line-height: 16px;
          font-size: 12px;
          padding: 0 8px;
          border-radius: 8px;
          background-color: #eaeef5;
          font-weight: bold;
          margin-right: 3px;
          vertical-align: unset;
        }
        &.checked {
          .count {
            background-color: #5982fe;
            color: @white;
          }
        }
      }
    }
  }
  .ant-divider {
    margin: 16px 0;
  }
  .search-item {
    margin-right: 24px;
    width: 240px;
    .ant-select {
      width: 100%;
    }
    .search-text {
      color: rgba(107, 121, 142, 0.85);
      font-size: 14px;
      margin: 6px 0 2px 0;
    }
  }
}
.table {
  margin-top: 24px;
}
</style>
<route lang="yaml">
name: Target Clients
path: /target-clients/
meta:
  sort: 0
</route>
